﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Wicresoft.Logger;

namespace Wicresoft.Task.Common
{
    public abstract class IntervalTask : ITask
    {
        private Thread taskThread;
        private TimeSpan waitTime;
        private bool running;

        public string Name { get; set; }
        public int SleepInterval { get; set; }
        public dynamic Bag { get; set; }

        protected IntervalTask()
        {
            waitTime = new TimeSpan(0, 0, 30);
            taskThread = new Thread(() =>
            {
                while (running)
                {
                    try
                    {
                        Execute();
                    }
                    catch (Exception e)
                    {
                        Log.Exception("Scheduler", e);
                    }
                    if (running)
                        Thread.Sleep(SleepInterval);
                }
            });
        }

        public void OnStart()
        {
            running = true;
            taskThread.Start();
            Log.Debug("Scheduler", "Task {0} has been started.", this.Name);
        }
        public void OnStop()
        {
            running = false;
            if (!taskThread.Join(waitTime))
            {
                // 如果30秒内不能正常停止，则中止线程
                taskThread.Abort();
                taskThread.Join();
                Log.Debug("Scheduler", "Task {0} was terminated", Name);
            }
            else
            {
                Log.Debug("Scheduler", "Task {0}  stopped normally", Name);
            }
        }

        protected abstract void Execute();
    }
}
